<template>
	<el-menu router unique-opened background-color="#545c64" text-color="#fff" active-text-color="#ffd04b"
		:collapse="isCollapse" class="el-menu-vertical-demo">

		<!-- v-if和v-for不能在同一个标签使用 -->
		<template v-for="menu in menus">
			<!-- 如果后面的children存在就执行，不存在就不执行children -->
			<el-submenu :index="menu.route_full_path" v-if="menu.children?.length > 0">
				<template slot="title">
					<i :class="`el-icon-${menu.icon_name}`"></i>
					<span>{{ menu.menu_name }}</span>
				</template>
				<el-menu-item v-for="child in menu.children" :index="child.route_full_path">
					<template slot="title">
						<i :class="`el-icon-${child.icon_name}`"></i>
						<span>{{ child.menu_name }}</span>
					</template>
				</el-menu-item>
			</el-submenu>
			<el-menu-item :index="menu.route_full_path" v-else>
				<i :class="`el-icon-${menu.icon_name}`"></i>
				<span>{{ menu.menu_name }}</span>
			</el-menu-item>
		</template>

	</el-menu>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { Role } from '@/api';

export default {
	data() {
		return {
			menus: [],
		}
	},
	created() {
		this.load_role_menu();
		// 加载角色的操作按钮权限
		let role_id = sessionStorage.role_id;
		this.load_operation_permission({ role_id, resource_type: 3 });
	},
	computed: {
		...mapState('fold', ['isCollapse']),

	},
	methods: {
		...mapActions('route', ['route_list']),
		...mapActions('menu', ['menu_list']),
		...mapActions('operation', ['operation_list']),
		...mapActions('role', ['role_list']),
		...mapActions('role', ['load_operation_permission']),

		// 加载当前角色的权限菜单
		async load_role_menu() {
			// 当前角色id
			let role_id = sessionStorage.role_id;
			let { status, data } = await Role.menu_power({ role_id, type: 'tree', resource_type: 2 });
			if (status) {
				this.menus = data;
				// 查询是否需要初始化权限state
				let system_menu = data.find((menu) => menu.permission_code === 'system');
				// 拥有系统管理菜单
				if (system_menu) {
					this.init_permission_state();
				}
			}
		},
		// 初始化store的权限state
		init_permission_state() {
			this.role_list();
			this.route_list();
			this.menu_list();
			this.operation_list();
		}
	},
}
</script>

<style lang="less" scoped>
.el-menu {
	// width: 200px;
	border: none;

}

.el-menu-vertical-demo:not(.el-menu--collapse) {
	width: 200px;
	min-height: 400px;
}
</style>
